<template>
  <div class="customer">
    <ListTab v-model="activeId" :show-header="!showMobilePage" :tabs="tabListData" is-table @tabClick="handleTabClick"/>
    <div :class="{'mobile-table mobile-pt mobile-el-pagination mobile-min-height':showMobilePage}" class="table-list min-fill-page">
      <ListCount
        :show-title="false"
        :list="listCount"
        :btn-style="listCountBtnStyle"
        :span-num="6"
        :class="{'mobile-list-count': showMobilePage}"
        :style="showMobilePage?'':{marginBottom: '20px', right: 0}"
        mode-type="oneCell"
        @fetchData="getListCount"/>
      <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
        <FilterInput
          ref="FilterToolRef"
          v-model="filterInput"
          :filter-list="filterList"
          show-search-btn
          is-show-config
          class="FilterTool"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"/>
        <div class="table-top-opeator-bar" style="margin-right: 236px">
          <create-button v-if="hasRouteAuth('mengli:inventory:add')" :add-name="'新建'" :create-link-name="'mengliInventoryCreate'" class="btn-right-item"/>
        </div>
      </div>
      <div v-loading="listLoading" style="min-height: 300px">
        <u-table
          v-if="list.items.length > 0"
          ref="customerTableRef"
          :data="list.items"
          :border="true"
          :row-height="rowHeight()"
          :height="setTableHeight"
          beautify-table
          header-drag-style
          use-virtual
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          hightlight-current-row
          @sort-change="sortMethod">
          <u-table-column align="left" label="SKU编码" min-width="150">
            <template slot-scope="scope">
              <!-- <span class="link" @click="goDetail(scope.row.id)">{{ scope.row.code }}</span> -->
              <el-tooltip v-if="scope.row.code" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.code }}</div>
                <div class="ellipsis link" @click="goDetail(scope.row.id)">{{ scope.row.code }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="标题" min-width="220">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.title" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="销售量" min-width="120" sortable="custom" prop="salesVolume">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="当前已出库数量"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              {{ scope.row.salesVolume | filterNon }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="待发货数量" min-width="150" sortable="custom" prop="unShipCount">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="当前订单未发货数量统计"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              {{ scope.row.unShipCount | filterNon }}
            </template>
          </u-table-column>
          <u-table-column align="right" label="成本价(元)" min-width="120" sortable="custom" prop="cost">
            <template slot-scope="scope">
              <PriceColumn :real-val="scope.row.cost" :price="scope.row.cost" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="商品属性" min-width="100">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.type" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.type }}</div>
                <div class="ellipsis">{{ scope.row.type }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="库存" min-width="100">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="总库存-已发货"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.inventoryCount || scope.row.inventoryCount === 0" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.inventoryCount }}</div>
                <div class="ellipsis">{{ scope.row.inventoryCount }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="实际可发库存" sortable="custom" min-width="150" prop="canShipCount">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="总库存-销售量-待发货数量"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              {{ scope.row.canShipCount | filterNon }}
            </template>
          </u-table-column>
          <u-table-column align="left" label="库存安全值" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.inventorySecurityVal" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="库存误差" min-width="110">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="共创库存-ERP库存（不包含今日数据）"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <ToolTip :content="scope.row.inventoryDeviation" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="入库商品误差" min-width="140">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="共创入库商品数量-ERP入库商品数量（不包含今日数据）"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockInDeviation" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="出库商品误差" min-width="140">
            <template slot="header" slot-scope="scope">
              <div class="table-header">
                <div class="flex">
                  <span class="label">{{ scope.column.label }}</span>
                  <tipIcon content="共创出库商品数量-ERP出库商品数量（不包含今日数据）"/>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <ToolTip :content="scope.row.stockOutDeviation" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="待盘点库存" min-width="100">
            <template slot-scope="scope">
              <ToolTip :content="scope.row.pendingInventory" />
            </template>
          </u-table-column>
          <u-table-column align="left" label="仓库" min-width="100">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.repositoryName" :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.repositoryName }}</div>
                <div class="ellipsis">{{ scope.row.repositoryName }}</div>
              </el-tooltip>
              <div v-else>--</div>
            </template>
          </u-table-column>
          <u-table-column align="left" label="IP形象" min-width="165">
            <template slot-scope="scope">
              <el-tooltip :open-delay="800" class="item" placement="top" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ `${scope.row.ipName || '--'}/${scope.row.ipSeriesName || '--'}` }}</div>
                <div class="ellipsis">{{ `${scope.row.ipName || '--'}/${scope.row.ipSeriesName || '--'}` }}</div>
              </el-tooltip>
            </template>
          </u-table-column>
          <u-table-column align="left" label="入库时间" min-width="165" sortable="custom" prop="inventoryTime">
            <template slot-scope="scope">
              <span v-if="scope.row.inventoryTime">{{ scope.row.inventoryTime/1000 | standardFormat('YYYY/MM/DD HH:mm:ss') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建时间" min-width="165" sortable="custom" prop="createTime">
            <template slot-scope="scope">
              <span v-if="scope.row.createTime">{{ scope.row.createTime/1000 | standardFormat('YYYY/MM/DD HH:mm:ss') }}</span>
              <span v-else>--</span>
            </template>
          </u-table-column>
          <u-table-column align="left" label="创建人" min-width="80">
            <template slot-scope="scope">
              {{ scope.row.creator || '--' }}
            </template>
          </u-table-column>
          <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" style="display:flex;">
                <div v-if="hasRouteAuth('mengli:inventory:read')" class="button-text" @click="goDetail(scope.row.id)">查看</div>
                <div v-if="hasRouteAuth('mengli:inventory:edit')" :class="{'bl':hasRouteAuth('mengli:inventory:read')}" class="button-text" @click="goCreate(scope.row)">编辑</div>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item v-if="hasRouteAuth('mengli:inventory:read')" style="width:90px;text-align: center" @click.native="goDetail(scope.row.id)">
                  <div>查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('mengli:inventory:edit')" @click.native="goCreate(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </u-table-column>
        </u-table>
        <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <fixed-pagination>
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="filterInput"
            :filter-list="filterList"
            show-search-btn
            show-mobile-icon
            class="FilterTool"
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"/>
          <createBtn
            v-if="hasRouteAuth('mengli:inventory:add')"
            mobile-table
            @click.native="createOrder"/>
        </template>
        <template v-else>
          <span style="flex:1;"/>
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :page-sizes="[20, 50, 100, 250, 500]"
            layout="total, prev, pager, next, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </template>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import setting from '@/assets/setting.png';
import icon1 from '@/assets/mengli/inventory/icon1.png';
import icon2 from '@/assets/dataDisplay/rmb.png';
import icon3 from '@/assets/mengli/inventory/icon3.png';
import icon5 from '@/assets/mengli/inventory/icon5.png';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ImportButton from '@/components/ImportButton';
import ExportButton from '@/components/ExportButton';
import createButton from '@/components/CreateButton';
import createBtn from '@/components/Common/baseComponent/createBtn';
import tipIcon from '@/assets/setting/tip.png';
import Title from '@/components/Title';
import ListCount from '@/components/Common/listCount';
import ListTab from '@/components/ListTab';
import { getInventoryList, getInventoryRepo, getInventoryStatistics } from '@/api/mengli';
import { standardFormat } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import { tabListData, handleTabChange, getSkuDiffNumFunc } from './utils';
import axios from 'axios';
import mobileTable from '@/mixins/mobileTable';

export default {
  filters: {
    standardFormat,
    moneyFilter,
    filterNon(val) {
      return (val !== 0 && !val) ? '--' : val;
    }
  },
  components: {
    ImportButton,
    ExportButton,
    createButton,
    createBtn,
    Title,
    EmptyPlaceholder,
    ListCount,
    ListTab
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      icon1,
      icon2,
      icon3,
      icon5,
      activeId: '0', tipIcon,
      tabListData,
      setting,
      repositoryOptions: [],
      filterInput: {},
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      statistics: null,
      listLoading: true,
      page: 1,
      perPage: 20,
      sortType: '',
      sortName: '',
      cacheMonthTime: null,
      rangeKeyArr: [{
        attr: 'createTime',
        start: 'createStart',
        end: 'createEnd',
        type: 'time'
      }, {
        attr: 'inventoryTime',
        start: 'inventoryStart',
        end: 'inventoryEnd',
        type: 'time'
      }, {
        attr: 'unShipCount',
        start: 'unShipCountMin',
        end: 'unShipCountMax',
        type: 'fansNums'
      }, {
        attr: 'canShipCount',
        start: 'canShipCountMin',
        end: 'canShipCountMax',
        type: 'fansNums'
      }],
      cancelToken: null
    };
  },
  computed: {
    uploadParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      return { ...params };
    },
    listCount() {
      return [{
        label: '入库数量',
        icon: icon1,
        data: this.statistics ? this.statistics['inventoryCount'] : ''
      }, {
        label: '入库总成本',
        icon: icon2,
        data: this.statistics ? this.statistics['inventoryTotalCost'] : ''
      }, {
        label: '出库数量',
        icon: icon3,
        data: this.statistics ? this.statistics['deliveryCount'] : ''
      }, {
        label: '出库总成本',
        icon: icon5,
        data: this.statistics ? this.statistics['deliveryTotalCost'] : ''
      }
      // , {
      //   label: '期末库存数量',
      //   data: this.statistics ? this.statistics['currentInventoryCount'] : ''
      // }, {
      //   label: '期末库存成本',
      //   data: this.statistics ? this.statistics['currentInventoryCost'] : ''
      // }
      ];
    },
    listCountBtnStyle() {
      const data = {
        position: 'absolute',
        right: '0px',
        bottom: '-52px',
        zIndex: '20'
      };
      if (this.showMobilePage) {
        data.right = '10px';
        data.bottom = '-36px';
      }
      return data;
    },
    filterList() {
      const arr = [
        { keyword: 'code', name: 'SKU编码', labelWidth: '100px', type: 'input' },
        { keyword: 'title', name: '标题', labelWidth: '100px', type: 'input' },
        { keyword: 'type', name: '商品属性', labelWidth: '100px', type: 'input' },
        // { keyword: 'supplier', name: '供应商', type: 'input' },
        { keyword: 'ipName', name: 'IP形象', labelWidth: '100px', type: 'input' },
        { keyword: 'ipSeriesName', name: 'IP系列', labelWidth: '100px', type: 'input' },
        { keyword: 'creator', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'unShipCount', name: '待发货数量', labelWidth: '100px', type: 'inputRange', isRequired: true, startPlaceholder: '最小数量', endPlaceholder: '最大数量', max: 999999999 },
        { keyword: 'canShipCount', name: '实际可发库存', labelWidth: '100px', type: 'inputRange', isRequired: true, startPlaceholder: '最小数量', endPlaceholder: '最大数量', max: 999999999 },
        { keyword: 'repositoryId', name: '仓库', type: 'select', options: this.repositoryOptions },
        { keyword: 'inventoryDeviation', name: '库存误差', type: 'select', options: this.stockStatus },
        { keyword: 'stockInDeviation', name: '入库商品误差', type: 'select', options: this.stockStatus },
        { keyword: 'stockOutDeviation', name: '出库商品误差', type: 'select', options: this.stockStatus },
        { keyword: 'pendingInventory', name: '待盘点库存', type: 'select', options: this.stockStatus },
        { keyword: 'inventoryTime', name: '入库时间', labelWidth: '100px', type: 'rangeDate', format: 'yyyy/MM/dd HH:mm:ss' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', type: 'rangeDate', format: 'yyyy/MM/dd HH:mm:ss' }
      ];
      return arr;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 280 : 254;
    },
    stockStatus() {
      return [
        { label: '有', value: 1 },
        { label: '无', value: 0 }
      ];
    }
  },
  created() {
    this.setActiveId();
  },
  methods: {
    init() {
      getSkuDiffNumFunc();
      if (this.$route.query.code) {
        this.filterInput = this.$route.query;
      }
      this.fetchData(true);
      this.getInventoryRepo();
    },
    setActiveId() {
      if (!this.hasRouteAuth('mengli:inventory:read')) {
        if (this.hasRouteAuth('mengli:inventoryLog:read')) {
          this.activeId = '1';
          this.$router.push({ name: 'mengliInventoryLog' });
        } else if (this.hasRouteAuth('mengli:skuLog:read')) {
          this.activeId = '2';
          this.$router.push({ name: 'mengliSkuLog' });
        } else if (this.hasRouteAuth('mengli:settleAccountsLog:read')) {
          this.activeId = '3';
          this.$router.push({ name: 'mengliSettleAccountsLog' });
        }
      } else {
        this.init();
      }
    },
    getListCount(val) {
      this.cacheMonthTime = val;
      const params = {
        monthTime: val
      };
      getInventoryStatistics(params).then(res => {
        if (res.code === 200) {
          this.statistics = res.data;
        }
      }).catch(err => {
        console.log(err);
        // this.$message({ type: 'error', message: err.message });
      });
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    mapKey(data) {
      const arr = [];
      data.map(item => {
        const arrItem = {
          value: item.repositoryId,
          label: item.repositoryName
        };
        arr.push(arrItem);
      });
      return arr;
    },
    getInventoryRepo() {
      getInventoryRepo().then(res => {
        this.repositoryOptions = this.mapKey(res.data.items);
      }).catch(err => {
        console.log(err);
        this.$message({ type: 'error', message: err.message });
      });
    },
    hasRouteAuth,
    fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.filterInput));
      /* if (params.createTime && params.createTime.length === 2) {
        params.createStart = Math.round(params.createTime[0] / 1000);
        params.createEnd = Math.round(params.createTime[1] / 1000);
      }
      if (params.inventoryTime && params.inventoryTime.length === 2) {
        params.inventoryStart = Math.round(params.inventoryTime[0] / 1000);
        params.inventoryEnd = Math.round(params.inventoryTime[1] / 1000);
      }
      delete params.createTime;
      delete params.inventoryTime; */
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      this.listLoading = true;
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.cancelToken = source;
      getInventoryList(params, source.token).then(({ data }) => {
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
      }, result => {
        this.listLoading = false;
      }).catch(e => {
        console.error(e);
      });
      this.cacheMonthTime && this.getListCount(this.cacheMonthTime);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.filterInput = {};
      this.queryClick();
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },

    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    goCreate(item = null) {
      if (item) {
        if (item.isReleated === 1) {
          this.$message.closeAll();
          this.$message.warning('该库存已有关联订单，不可编辑');
          return false;
        }
        this.$router.push({
          name: 'mengliInventoryEdit',
          params: {
            id: item.id
          }
        });
      } else {
        this.$router.push({
          name: 'mengliInventoryCreate'
        });
      }
    },
    goDetail(id) {
      this.$router.push({
        name: 'mengliInventoryDetail',
        params: {
          id: id
        }
      });
    },
    createOrder() {
      this.$router.push({
        name: 'mengliInventoryCreate'
      });
    },
    handleTabClick(id) {
      handleTabChange(id, this);
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.link {
  color: #406eff;
  cursor: pointer;
}
.mobile-list-count {
  margin-bottom: 42px;
}
.customer {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 24px 24px 55px 24px;
  }
}
.table-header {
  display: inline-block;
  .flex {
    display: flex;
    align-items: center;
  }
  .tip-icon {
    width: 14px;
    margin-left: 3px;
  }
}
</style>

